<template>
	<view class="voice-module">
		<u-navbar :title="$t('dating.VoiceRecording')" :autoBack="false" @leftClick="leftClick" bgColor="#F6F6F6"
			titleStyle="color: #000000" placeholder>
		</u-navbar>
		<!-- 语音动画 -->
		<view class="record-content" v-if="recorderManagerOpen">
			<view class="seconds">{{ duration }}</view>
		</view>
		<view class="voice-detail">
			<view class="title" v-if="!voice">{{ $t("friend.Voicenotsetyet") }}</view>
			<view class="play-view" v-else>
				<view class="play">{{ $t("friend.Clicktoplay") }}</view>
				<view class="shanchu-view" @click="handleDelete">
					<view class="iconfont icon-shanchu shanchu"></view>
					<view class="Delete">{{ $t("index.Delete") }}</view>
				</view>
			</view>
			<view class="bofang-view" :style="voice ? 'background: #61BDB2;' : ''" @tap="playVoice">
				<view class="iconfont icon-bofang bofang" :style="voice ? 'color: #ffffff;' : ''" v-if="!bofang || !voice">
				</view>
				<image src="@/static/image/chart/play-right.png" class="play-right" v-else-if="bofang && voice" />
				<image src="@/static/image/friend/sound_wave.png" class="sound_wave" />
			</view>
			<view class="talk-view">
				<view class="yuyin-view" @touchstart="startRecord" @touchend="overRecord">
					<view class="iconfont icon-yuyin1 yuyin1"></view>
				</view>
				<view class="Hold">{{ $t("friend.HoldtoTalk") }}</view>
			</view>
		</view>
		<view class="btn" @click="handlePost">{{ $t("friend.post") }}</view>

		<!-- #ifdef H5 -->
		<recorder ref="recorderCom" @error="recorderError" @success="recorderSuccess" @start="recorderStart"></recorder>
		<!-- #endif -->
	</view>
</template>

<script>
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	import moment from "moment";
	import config from "@/config/app.config";
	import store from "@/store/index";
	import {
		updateFriendInfo
	} from "@/services/makeFriend";
	import {
		debounce
	} from "@/utils/util.js";
	// 引入H5录音组件
	import recorder from "@/components/recorder.vue";

	export default {
		data() {
			return {
				voice: "",
				recorderManagerOpen: false,
				duration: "",
				startTime: "",
				audio: "",
				bofang: false,
				formData: "",
			};
		},
		components: {
			recorder,
		},
		methods: {
			/*H5录音失败*/
			recorderError(e) {
				//console.log('recorderError', e);
				if (e) {
					uni.showToast({
						title: e,
						icon: "error",
					});
				}
				setTimeout(() => {
					this.recorderManagerOpen = false;
				}, 300);
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = undefined;
				}
			},
			/*H5录音成功*/
			async recorderSuccess(res) {
				const sec = moment().diff(this.startTime, "seconds");
				if (sec < 1) {
					return;
					// return uni.showToast({
					//   title: this.$t("chat.Record-tips"),
					//   icon: "error",
					// });
				}
				console.log("监听语音结束");
				this.voicePath = res.localUrl;
				if (this.voicePath) {
					uni.showLoading()
				}
				let a = uni.uploadFile({
					url: config.server + "/app/oss/upload", // 仅为示例，非真实的接口地址
					filePath: res.localUrl,
					name: "file",
					header: {
						Authorization: `Bearer ${store.state.token}`,
						version: config.version,
					},
					formData: {
						user: "test",
					},
					success: (res) => {
						const resp = JSON.parse(res.data);
						console.log("回调", res, resp);
            
            // uni.setClipboardData({
            //   data: resp.data.url,
            //   success: (res) => {
            //     console.log('复制成功')
            //   }
            // })
						if (resp.code == 200) {
							setTimeout(() => {
								this.voice = resp.data.url;
								this.playCreate()
								uni.hideLoading()
							}, 1000);
						}
					},
				});
			},
			//删除录音
			handleDelete() {
				this.voice = "";
				this.playDestroy()
				// this.$t("chat.Record-tips")
				uni.showToast({
					title: this.$t("friend.VoiceDelete"),
					icon: "error",
				});
			},
			//暂停播放
			playStop() {
				innerAudioContext.pause();
				this.bofang = false;
			},
			//长按录音
			startRecord() {
				uni.showLoading()
				// #ifdef H5
				this.$refs.recorderCom.start();
				// #endif

				// #ifdef APP-PLUS
				recorderManager.start();
				// #endif

			},
			/**
			 * 开始录音，初始化计时器
			 */
			recorderStart() {
				uni.hideLoading()
				this.duration = 0;
				this.recorderManagerOpen = true;
				this.startTime = moment();
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = undefined;
				}
				this.timer = setInterval(() => {
					this.duration = moment().diff(this.startTime, "seconds");
				}, 100);
			},
			//结束录音
			overRecord() {
				this.recorderManagerOpen = false;
				const sec = moment().diff(this.startTime, "seconds");
				if (sec < 1) {
					this.startTime = moment();
					// if (!this.$store.state.isWebview) {
					  this.$refs.recorderCom.stop();
					// }
					uni.showToast({
						title: this.$t("chat.Record-tips"),
						icon: "error",
					});
					return;
				}
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = undefined;
				}
				// if (this.$store.state.isWebview) {
				//   recorderManager.stop({
				//     format: "mp3",
				//   });
				//   return
				// }
				// #ifdef H5
				this.$refs.recorderCom.stop();
				// #endif
				// #ifdef APP-PLUS
				recorderManager.stop({
				  format: "mp3",
				});
				// #endif
			},
			handleVioceOver() {
        /* 监听开始录音 */
        recorderManager.onStart(() => {
          this.recorderStart()
        })
        
				/**监听语音结束*/
				recorderManager.onStop(async (res) => {
					const sec = moment().diff(this.startTime, "seconds");
					if (+sec < 1) {
						return uni.showToast({
							title: this.$t("chat.Record-tips"),
							icon: "error",
						});
					}
					console.log("监听语音结束");
					this.voicePath = res.tempFilePath;
					if (this.voicePath) {
						uni.showLoading()
					}
					let a = uni.uploadFile({
						url: config.server + "/app/oss/upload", // 仅为示例，非真实的接口地址
						filePath: res.tempFilePath,
						name: "file",
						header: {
							Authorization: `Bearer ${store.state.token}`,
							version: config.version,
						},
						formData: {
							user: "test",
						},
						success: (res) => {
							const resp = JSON.parse(res.data);
							console.log("回调", res, resp);
							if (resp.code == 200) {
								setTimeout(() => {
									this.voice = resp.data.url;
									this.playCreate()
									uni.hideLoading()
								}, 1000);
							}
						},
					});
				});
			},
			// 创建播放音频
			playCreate() {
				this.audio = uni.createInnerAudioContext();
				this.audio.autoplay = false;
				this.audio.src = this.voice; //音频地址
			},
			// 销毁音频
			playDestroy() {
				this.bofang = false;
				if (this.audio) {
					this.audio.destroy();
				}
				this.audio = undefined;
			},
			//播放语音
			playVoice() {
				// if (this.audio) {
				//   this.audio.destroy();
				// }
				// this.bofang = true;
				// this.audio = uni.createInnerAudioContext();
				// this.audio.autoplay = true;
				// this.audio.src = this.voice; //音频地址
				// this.audio.play(); //执行播放
				// this.audio.onEnded(() => {
				//   this.audio.destroy();
				//   this.audio = undefined;
				//   this.bofang = false;
				// });
				if(!this.audio) {
						this.playCreate()
				}
				this.bofang = !this.bofang
				if (this.bofang) {
					this.audio.play(); // 执行播放
				} else {
					this.audio.pause();
					this.audio.seek(0)
				}
				this.audio.onEnded(() => {
					this.bofang = false;
				});
			},
			//发布语音
			async handlePost() {
				// this.formData.chat = this.value11 ? 1 : 0;
				// if (!this.voice) {
				//   uni.showToast({
				//     title: this.$t("dating.makeVoice"),
				//     icon: "error",
				//   });
				//   return;
				// }
				console.log(this.voice, 'this.voice')
				this.formData.voice = this.voice;
				console.log(this.formData, "this.formData)");
				const resp = await updateFriendInfo(this.formData);
				if (!resp.success) return;
				uni.redirectTo({
					url: '/pagesDiscover/friendsInformation/FriendsInformation'
				});
			},
		},
		onLoad(option) {
			this.formData = this.$store.state.friendsInformation;
			this.voice = this.formData.voice;
			if (this.voice) {
				this.playCreate()
			}
			this.getPrePages() // 获取上一个页面的路径已经参数
			this.handleVioceOver();
		},
		onHide() {
			this.playDestroy()
		},
		onUnload() {
			this.playDestroy()
		},
	};
</script>

<style lang="scss" scoped>
	.voice-module {
		padding: 30upx;
		box-sizing: border-box;

		.voice-detail {
			padding: 30upx;
			background: #ffffff;
			border-radius: 20upx;

			.play-view {
				display: flex;
				margin-top: 60upx;
				align-items: center;
				justify-content: space-between;

				.play {
					font-size: 30upx;
					font-weight: 400;
					color: #000000;
				}

				.shanchu-view {
					display: flex;
					align-items: center;

					.shanchu {
						color: #fe6600;
						font-size: 24upx;
					}
				}

				.Delete {
					font-size: 26upx;
					font-weight: 400;
					color: #fe6600;
				}
			}

			.title {
				text-align: center;
				font-size: 30upx;
				font-weight: 400;
				color: #000000;
				margin-top: 60upx;
			}

			.bofang-view {
				margin-top: 60upx;
				height: 78upx;
				padding: 15upx 18upx;
				background: #d0ede9;
				border-radius: 39upx;
				display: flex;
				align-items: center;
				box-sizing: border-box;

				.bofang {
					color: #e9f3f2;
					font-size: 48upx;
				}

				.sound_wave {
					width: 526upx;
					height: 24upx;
					margin-left: 20upx;
				}
			}

			.talk-view {
				margin-top: 90upx;
				text-align: center;

				.yuyin-view {
					width: 120upx;
					height: 120upx;
					background: #e9f3f2;
					border-radius: 50%;
					margin: 0 auto;
					display: flex;
					align-items: center;
					justify-content: center;

					.yuyin1 {
						color: #61bdb2;
						font-size: 60upx;
					}
				}

				.Hold {
					margin-top: 23upx;
					font-size: 24upx;
					font-weight: 400;
					color: #878787;
				}
			}
		}

		.btn {
			position: fixed;
			bottom: 20upx;
			width: 90%;
			height: 90upx;
			background: #61bdb2;
			border-radius: 20upx;
			line-height: 90upx;
			text-align: center;
			font-size: 30upx;
			font-weight: 500;
			color: #ffffff;
		}
	}

	.record-content {
		width: 480rpx;
		height: 130rpx;
		background: #ffffff;
		border-radius: 30rpx;
		position: absolute;
		top: 50%;
		left: 50%;
		transition: all 0.1s;
		transform: translate(-50%, -50%);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 30;
	}

	.record-content::after {
		position: absolute;
		content: "";
		width: 0px;
		height: 0px;
		border: 30rpx solid white;
		border-top-color: white;
		border-bottom-color: transparent;
		border-left-color: transparent;
		border-right-color: transparent;
		top: 130rpx;
	}

	.seconds {
		width: 368rpx;
		height: 24rpx;
		background-image: url("../../static/image/in_voice.png");
		background-size: 368rpx 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26rpx;
		font-family: Source Han Sans CN;
		font-weight: 400;
		color: #ff5551;
	}

	.play-right {
		width: 48upx;
		height: 48upx;
	}
</style>